package com.example.vue_shop.utils;


import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回对象.
 * @author lipengwei
 */
@ApiModel(value = "ResultN", description = "封装好的接口响应对象,返回为转为json格式的字符串")
public class ResultN {
    @ApiModelProperty(value = "状态", name = "status", example = "true", dataType = "boolean", required = true)
    private boolean status;
    @ApiModelProperty(value = "数据", name = "data", example = "name=张三",
            dataType = "Map<String, Object>", allowEmptyValue = true)
    private Map<String, Object> data;
    @ApiModelProperty(value = "描述信息", name = "message", example = "请求成功！", dataType = "String", allowEmptyValue = true)
    private String message;

    private static volatile ResultN resultN = null;

    private ResultN() {

    }

    /**
     * 成功返回方法.
     * @param data 返回数据
     * @param message 返回消息.
     * @return String
     */
    public static String success(Map<String, Object> data, String message) {
        if (resultN == null) {
            synchronized (ResultObj.class) {
                if (resultN == null) {
                    resultN = new ResultN();
                }
            }
        }

        resultN.setData(data);
        resultN.setMessage(message);
        resultN.setStatus(true);
        System.out.println("=======" + JSON.toJSONString(resultN));
        return JSON.toJSONString(resultN);
    }

    public static String success(String message) {
        if (resultN == null) {
            synchronized (ResultObj.class) {
                if (resultN == null) {
                    resultN = new ResultN();
                }
            }
        }
        resultN.setData(new HashMap<>(0));
        resultN.setMessage(message);
        return JSON.toJSONString(resultN);
    }

    /**
     * 失败方法.
     * @param message 返回信息
     * @return String
     */
    public static String error(String message) {
        if (resultN == null) {
            synchronized (ResultObj.class) {
                if (resultN == null) {
                    resultN = new ResultN();
                }
            }
        }
        resultN.setStatus(false);
        resultN.setData(new HashMap<>(0));
        resultN.setMessage(message);
        return JSON.toJSONString(resultN);
    }

    /**
     * 为了转换json字符串不丢失属性，需要setget方法
     * @return
     */
    public boolean getStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
